package com.itheima.包装类.myinteger;

//二分查找
public class BinarySearchDemo {
    public static void main(String[] args) {
        //需求:顺序排好的一个数组
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        //需求:输入要查的数字
        int num = 3;

        //定义一个方法二分查找
        int index = binarySearch(arr, num);
        System.out.println(index);
    }

    private static int binarySearch(int[] arr, int num) {
        //循环的条件 最小索引值不大于最大索引值
        int min = 0;
        int max = arr.length - 1;

        //循环查找
        while (min <= max) {
            int mid = (min + max) / 2;
            if (arr[mid] < num) {
                min = mid + 1;
            } else if (arr[mid] > num) {
                max = mid - 1;
            } else {
                return mid;
            }

        }
        return -1;
    }
}
